<template>
  <div v-loading="loading" element-loading-text="加载中..." class="into_storage_detail">
    <div class="main">
      <header class="header">
        <div class="title">
          <div class="text">
            <i class="iconfont icon-detail"></i>
            <span>入库详情</span>
          </div>
          <HStatus v-if="DetailStore?.status === 1" type="warning">待审核</HStatus>
          <HStatus v-if="DetailStore?.status === 2" type="warning">待入库</HStatus>
          <HStatus v-if="DetailStore?.status === 3" type="info">已驳回</HStatus>
          <HStatus v-if="DetailStore?.status === 4" type="success">已入库</HStatus>
          <HStatus v-if="DetailStore?.status === 5" type="error">已作废</HStatus>
        </div>
        <div class="btn_group">
          <HPlainButton @click="printBtn">打印</HPlainButton>
          <template v-if="DetailStore?.status === 2">
            <HPlainButton @click="outboundBtn">入库</HPlainButton>
            <HPlainButton type="error" @click="cancellationBtn">作废</HPlainButton>
          </template>
        </div>
      </header>

      <div class="divider_line"></div>

      <body class="body">
        <!-- 入库信息 -->
        <div ref="intoStorageInfoRef" class="into_storage_info">
          <div class="title">入库信息</div>
          <div class="info_list">
            <div class="info_item_container">
              <div class="info_item">
                <div class="label">入库单号:</div>
                <div class="value">{{ DetailStore?.inboundNo }}</div>
              </div>
              <div class="info_item">
                <div class="label">仓库类型:</div>
                <div class="value">{{ storeType[DetailStore?.storeType]?.title }}</div>
              </div>
            </div>
            <div class="info_item_container">
              <div class="info_item">
                <div class="label">单据类型:</div>
                <div class="value">{{ DetailStore?.type }}</div>
              </div>
              <div class="info_item">
                <div class="label">单据来源:</div>
                <div class="value">{{ source[DetailStore?.source - 1]?.title }}</div>
              </div>
            </div>
            <div class="info_item_container alignment">
              <div class="info_item">
                <div class="label">制单日期:</div>
                <div class="value">{{ DetailStore?.createTime }}</div>
              </div>
              <div class="info_item">
                <div class="label">预计入库时间:</div>
                <div class="value">{{ DetailStore?.estimateTime }}</div>
              </div>
            </div>
            <div class="info_item">
              <div class="label">单据备注:</div>
              <div class="value">{{ DetailStore?.remark }}</div>
            </div>
          </div>
        </div>

        <!-- 物流信息 -->
        <div v-if="DetailStore?.status == 4" ref="logisticsInfoRef" class="logistics_info">
          <div class="title">物流信息</div>
          <div class="info_list">
            <div class="info_item">
              <div class="label">物流名称:</div>
              <div class="value">{{ DetailStore?.logisticsName }}</div>
            </div>
            <div class="info_item">
              <div class="label">单号:</div>
              <div class="value">{{ DetailStore?.logisticsNo }}</div>
            </div>
            <div class="info_item">
              <div class="label">物流备注:</div>
              <div class="value">{{ DetailStore?.logisticsRemark }}</div>
            </div>
          </div>
        </div>

        <!-- 操作日志 -->
        <div ref="operateInfoRef" class="operate_info">
          <div class="title">操作日志</div>
          <div class="info_list">
            <div class="info_item">
              <div class="label">制单人:</div>
              <div class="value">{{ DetailStore?.createEmp }}</div>
            </div>
            <template v-if="DetailStore?.rejectTime">
              <div class="info_item">
                <div class="label">驳回人:</div>
                <div class="value">{{ DetailStore?.rejectEmp }}</div>
              </div>
              <div class="info_item">
                <div class="label">驳回时间:</div>
                <div class="value">{{ DetailStore?.rejectTime }}</div>
              </div>
              <div class="info_item">
                <div class="label">驳回备注:</div>
                <div class="value">{{ DetailStore?.rejectRemark }}</div>
              </div>
            </template>
            <template v-if="DetailStore?.reviewTime">
              <div class="info_item">
                <div class="label">审核人:</div>
                <div class="value">{{ DetailStore?.reviewEmp }}</div>
              </div>
              <div class="info_item">
                <div class="label">审核时间:</div>
                <div class="value">{{ DetailStore?.reviewTime }}</div>
              </div>
              <div class="info_item">
                <div class="label">审核备注:</div>
                <div class="value">{{ DetailStore?.reviewRemark }}</div>
              </div>
            </template>
            <template v-if="DetailStore?.inboundTime">
              <div class="info_item">
                <div class="label">入库人:</div>
                <div class="value">{{ DetailStore?.inboundEmp }}</div>
              </div>
              <div class="info_item">
                <div class="label">入库时间:</div>
                <div class="value">{{ DetailStore?.inboundTime }}</div>
              </div>
              <div class="info_item">
                <div class="label">入库备注:</div>
                <div class="value">{{ DetailStore?.inboundRemark }}</div>
              </div>
            </template>
            <template v-if="DetailStore?.cancelTime">
              <div class="info_item">
                <div class="label">作废单操作人:</div>
                <div class="value">{{ DetailStore?.cancelEmp }}</div>
              </div>
              <div class="info_item">
                <div class="label">作废时间:</div>
                <div class="value">{{ DetailStore?.cancelTime }}</div>
              </div>
              <div class="info_item">
                <div class="label">作废备注:</div>
                <div class="value">{{ DetailStore?.cancelRemark }}</div>
              </div>
            </template>
          </div>
        </div>

        <!-- 产品列表 -->
        <div class="product_info" :style="productInfoStyle">
          <div class="title">
            <div class="line"></div>
            <h4 class="text">产品列表</h4>
          </div>
          <div class="table">
            <el-table
              :border="true"
              :data="commoditys"
              :summary-method="getSummaries"
              height="100%"
              resizable
              show-summary
              stripe
            >
              <template #empty>
                <el-empty description="暂无数据" />
              </template>
              <!-- 序号 -->
              <el-table-column
                fixed="left"
                label="序号"
                type="index"
                width="60"
                :align="'center'"
              />

              <!-- 类型 -->
              <el-table-column label="类型" show-overflow-tooltip width="100">
                <template #default="i">
                  {{ i.row.type == 1 ? '成品' : '物料' }}
                </template>
              </el-table-column>

              <!-- 产品名称 -->
              <el-table-column
                label="产品名称"
                min-width="100"
                prop="goodsName"
                show-overflow-tooltip
              />

              <!-- 型号 -->
              <!-- <el-table-column
                label="型号"
                min-width="100"
                prop="goodsModel"
                show-overflow-tooltip
              /> -->

              <!-- 规格 -->
              <el-table-column
                label="规格"
                min-width="100"
                prop="goodsSpecName"
                show-overflow-tooltip
              />

              <!-- 品牌 -->
              <!-- <el-table-column
                label="品牌"
                min-width="100"
                prop="goodsBrand"
                show-overflow-tooltip
              /> -->

              <!-- 分类 -->
              <el-table-column
                label="分类"
                min-width="120"
                prop="goodsType"
                show-overflow-tooltip
              />

              <!-- 单位 -->
              <el-table-column label="单位" prop="goodsUnit" show-overflow-tooltip width="100" />

              <!-- 仓库 -->
              <el-table-column label="仓库" min-width="150" prop="store" show-overflow-tooltip />

              <!-- 仓位 -->
              <el-table-column
                label="仓位"
                min-width="150"
                prop="storePosition"
                show-overflow-tooltip
              />

              <!-- 可用库存 -->
              <el-table-column prop="systemStock" show-overflow-tooltip label="可用库存" width="90">
                <template #header>
                  <span>可用库存</span>
                  <el-tooltip content="可用库存 = 即时库存 - 占用库存" placement="top">
                    <el-icon>
                      <QuestionFilled />
                    </el-icon>
                  </el-tooltip>
                </template>
              </el-table-column>

              <!-- 入库数量 -->
              <el-table-column label="入库数量" prop="qty" show-overflow-tooltip width="90" />

              <!-- 单价 -->
              <!-- <el-table-column label="单价" prop="price" show-overflow-tooltip width="90">
                <template #default="scope"> ￥{{ scope.row.price.toFixed(2) }} </template>
              </el-table-column> -->

              <!-- 金额 -->
              <!-- <el-table-column label="金额" prop="price" show-overflow-tooltip width="100">
                <template #default="scope">
                  ￥{{ (scope.row.price * scope.row.qty).toFixed(2) }}
                </template>
              </el-table-column> -->

              <!-- 备注 -->
              <el-table-column label="备注" prop="remark" show-overflow-tooltip width="100" />

              <!-- 操作 -->
              <el-table-column
                :label="[3, 4, 5].includes(DetailStore?.status) ? '条码' : '选择条码'"
                width="160"
                prop="stockCodeVos"
                fixed="right"
              >
                <template #default="scope">
                  <template v-if="[3, 4, 5].includes(DetailStore?.status)">
                    {{ scope.row.stockCodeVos[0].code }}
                  </template>
                  <template>
                    <HLink
                      v-if="scope.row.stockCodeVos?.length > 0"
                      @click="handleShowSelectSnCode(scope.row, scope.$index)"
                      >{{ scope.row.stockCodeVos[0].code }}</HLink
                    >
                    <HLink v-else @click="handleShowSelectSnCode(scope.row, scope.$index)"
                      >选择条码</HLink
                    >
                  </template>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </body>
    </div>

    <!-- 作废弹窗 -->
    <h-dialog v-model="cancellationDialog" title="确认作废此入库吗?" :loading="cancellationLoading">
      <el-form label-position="top" class="modal_form_content cancel_form">
        <el-form-item label="作废原因">
          <el-input
            v-model.trim="remark"
            maxlength="400"
            placeholder="请填写作废原因"
            type="textarea"
            show-word-limit
            resize="both"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <h-button is-modal type="primary" @click="cancellationConfirm">确认</h-button>
        <h-button
          is-modal
          @click="
            () => {
              cancellationDialog = false
              remark = ''
            }
          "
          >取消</h-button
        >
      </template>
    </h-dialog>

    <!-- 入库弹窗 -->
    <h-dialog v-model="outboundDialog" title="确认入库" :loading="confirmIntoStorageLoading">
      <div class="in_warehouse_dialog">
        <span class="tip">
          <i class="iconfont icon-warning"></i>
          若不选择物流，请直接点击确认按钮入库
        </span>
        <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          class="modal_form_content confirm_into_storage_form"
          label-position="top"
        >
          <!-- 物流名称 -->
          <el-form-item label="物流名称" prop="logisticsName">
            <el-select
              v-model="ruleForm.logisticsName"
              :loading="loadingEmp"
              :remote-method="inputValueSch"
              clearable
              filterable
              placeholder="物流名称"
              remote
              remote-show-suffix
            >
              <el-option
                v-for="(item, index) in modules"
                :key="index"
                :label="item.name"
                :value="item.name"
              />
            </el-select>
          </el-form-item>

          <!-- 物流条码 -->
          <el-form-item label="物流条码">
            <el-select
              v-model="ruleForm.logisticsCode"
              disabled
              filterable
              placeholder="物流条码"
            >
              <el-option
                v-for="(item, index) in modules"
                :key="index"
                :label="item.code"
                :value="item.code"
              />
            </el-select>
          </el-form-item>

          <!-- 物流单号 -->
          <el-form-item label="物流单号" prop="logisticsNo">
            <el-input v-model.trim="ruleForm.logisticsNo" placeholder="物流单号" />
          </el-form-item>

          <!-- 备注 -->
          <el-form-item label="备注" prop="remark">
            <el-input
              v-model.trim="ruleForm.remark"
              maxlength="400"
              placeholder="填写入库备注"
              type="textarea"
              show-word-limit
              resize="both"
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <HButton is-modal type="primary" @click="outboundConfirm">确认</HButton>
        <HButton is-modal @click="resetForm">取消</HButton>
      </template>
    </h-dialog>

    <!-- 在库选择 -->
    <h-drawer
      v-model="selectCodeDialogVisible"
      title="在库选择"
      :width="80"
      :loading="getInOutWarehouseSnCodeLoading"
    >
      <div class="select_code">
        <div class="header">
          <div class="info_list">
            <div class="info_item">
              <div class="label">产品名称:</div>
              <h-tooltip-text
                :text="currentOperateCommodity.goodsName || ''"
                :max-width="100"
                :height="16"
                width="auto"
              />
            </div>
            <div class="info_item">
              <div class="label">产品规格:</div>
              <h-tooltip-text
                :text="currentOperateCommodity.goodsSpecName || ''"
                :max-width="100"
                :height="16"
                width="auto"
              />
            </div>
            <div class="info_item">
              <div class="label">产品类型:</div>
              <h-tooltip-text
                :text="currentOperateCommodity.goodsType || ''"
                :max-width="100"
                :height="16"
                width="auto"
              />
            </div>
            <div class="info_item">
              <div class="label">产品编号:</div>
              <h-tooltip-text
                :text="currentOperateCommodity.code || ''"
                :max-width="100"
                :height="16"
                width="auto"
              />
            </div>
          </div>
          <div class="btn_group">
            <HPlainButton @click="onCreateCode">创建条码</HPlainButton>
            <el-input
              v-model.trim="keywordCode"
              clearable
              placeholder="条码"
              @keyup.enter="getInOutWarehouseSnCode"
              @clear="getInOutWarehouseSnCode"
            />
            <h-button type="primary" @click="getInOutWarehouseSnCode">搜索</h-button>
          </div>
        </div>
        <div class="table">
          <el-table
            ref="selectCodeTableRef"
            :border="true"
            :data="getListCode"
            height="100%"
            resizable
            stripe
            @selection-change="handleSnCodeSelectionChange"
          >
            <template #empty>
              <el-empty description="暂无数据" />
            </template>
            <el-table-column fixed show-overflow-tooltip type="selection" width="40" />
            <el-table-column fixed label="序号" type="index" width="60" />
            <el-table-column label="条码" width="140" prop="code" show-overflow-tooltip>
              <template #default="scope">
                <h-link @click="handleToSnCodeDetail(scope.row)">{{ scope.row.code }}</h-link>
              </template>
            </el-table-column>
            <el-table-column label="品牌" prop="goodsBrand" show-overflow-tooltip />
            <el-table-column label="名称" prop="goodsName" show-overflow-tooltip />
            <el-table-column label="型号" prop="goodsModel" show-overflow-tooltip />
            <el-table-column label="规格" prop="goodsSpecName" show-overflow-tooltip />
            <el-table-column label="所属仓库" prop="store" show-overflow-tooltip />
            <el-table-column label="仓位" prop="storePosition" show-overflow-tooltip />
          </el-table>
        </div>
        <div class="pagination">
          <Pagination
            ref="paginationRef"
            :list_total="totalCode"
            @size-change="getInOutWarehouseSnCode"
            @current-change="getInOutWarehouseSnCode"
          />
        </div>
      </div>
      <template #footer>
        <HButton is-modal type="primary" @click="onConfirmSelectSnCode">确定</HButton>
        <HButton is-modal @click="selectCodeDialogVisible = false">取消</HButton>
      </template>
    </h-drawer>

    <!-- 创建条码弹窗 -->
    <h-dialog v-model="CreateCodeDialog" title="创建条码" :loading="createCodeLoading">
      <el-form
        ref="createCodeRef"
        :model="createCode"
        :rules="CreateCoderules"
        class="modal_form_content"
        label-position="top"
        inline-message
      >
        <!-- 批次名称 -->
        <el-form-item label="批次名称" prop="name">
          <el-input v-model.trim="createCode.name" placeholder="请输入批次名称" />
        </el-form-item>

        <!-- 条码类型 -->
        <el-form-item label="条码类型">
          <el-radio-group v-model="createCode.type" class="ml-4" disabled>
            <el-radio :value="1">成品</el-radio>
            <el-radio :value="2">物料</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 产品型号 -->
        <el-form-item label="产品型号">
          <el-input
            v-model.trim="currentOperateCommodity.goodsModel"
            disabled
            placeholder="产品型号"
          />
        </el-form-item>

        <!-- 产品规格 -->
        <el-form-item label="产品规格">
          <el-input
            v-model.trim="currentOperateCommodity.goodsSpecName"
            disabled
            placeholder="产品规格"
          />
        </el-form-item>

        <!-- 条码数量 -->
        <el-form-item label="条码数量">
          <el-input
            v-model.trim="createCode.codeVos[0].qty"
            placeholder="条码数量"
            @input="createCode.codeVos[0].qty = createCode.codeVos[0].qty.replace(/[^0-9]/g, '')"
          />
        </el-form-item>

        <!-- 质保周期 -->
        <el-form-item label="质保周期">
          <el-input
            v-model.trim="createCode.codeVos[0].warrantyDay"
            placeholder="质保周期"
            @input="
              createCode.codeVos[0].warrantyDay = createCode.codeVos[0].warrantyDay.replace(
                /[^0-9]/g,
                '',
              )
            "
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <HButton is-modal type="primary" @click="onaddSave">确认</HButton>
        <HButton is-modal @click="CreateCodeDialog = false">取消</HButton>
      </template>
    </h-dialog>
  </div>
</template>

<script lang="ts" setup>
  import { CSSProperties, nextTick, onMounted, ref, watch } from 'vue'
  import { useRoute, useRouter } from 'vue-router'
  import * as _ from 'lodash'
  import Pagination from '../../../components/Pagination/index.vue'
  import { ElMessage, ElMessageBox, TableInstance } from 'element-plus'
  import {
    cancelStoreInbound,
    getInboundDetail,
    getInboundDetailMaterial,
    getLogisticsSelectList,
    getStoreCodeList,
    saveSureStoreInbound,
  } from '../../../api/store'
  import { addSave } from '../../../api/code'
  import userInbound from './userInbound'
  import { useTagsViewStore } from '@/store/modules/tagsView'
  import { SnCode } from './new/types'
  import routeComponentName from '@/config/route-component-name'

  defineOptions({
    name: routeComponentName.storage.inStorageDetail,
  })

  const { storeType, source } = userInbound()

  /**
   * 全局路由对象
   */
  const router = useRouter()

  /**
   * 保存之后,审核之前的每个产品选择的条码
   * 用于审核时选择新条码然后清空掉后，将审核之前选中的条码填充到表格里
   */
  const snCodeAfterSave = ref([])

  /**
   * 选择条码弹窗的显示状态
   */
  const selectCodeDialogVisible = ref(false)

  /**
   * 当前操作的产品,用于为指定产品选择条码
   */
  const currentOperateCommodity = ref(null)

  /**
   * 条码选择弹窗的表格组件实例
   */
  const selectCodeTableRef = ref<TableInstance | null>(null)

  /**
   * 获取未出入库条码加载
   */
  const getInOutWarehouseSnCodeLoading = ref(false)

  /**
   * 选择条码弹窗的确定按钮点击事件
   */
  const onConfirmSelectSnCode = () => {
    if (
      currentOperateCommodity.value.qty <
      commoditys.value[currentOperateCommodity.value.index].stockCodeVosTemp.length
    ) {
      ElMessageBox({
        title: '提示',
        message: '录入条码数量不能超过出库条码总数',
        type: 'error',
      })
      return
    }
    commoditys.value[currentOperateCommodity.value.index].stockCodeVosTemp.forEach((codeObj) => {
      commoditys.value[currentOperateCommodity.value.index].stockCodeVos.push({
        code: codeObj.code,
      })
    })

    selectCodeDialogVisible.value = false
  }

  /**
   * 显示选择条码弹窗
   */
  const handleShowSelectSnCode = (row, index: number) => {
    selectCodeDialogVisible.value = true
    currentOperateCommodity.value = { ...row, index: index }
    commoditys.value[index].stockCodeVosTemp = commoditys.value[index].stockCodeVosTemp.map((o) => {
      return { ...o, ...row }
    })
    nextTick(() => {
      getInOutWarehouseSnCode()
    })
  }

  /**
   * 获取未出入库的条码
   */
  const getInOutWarehouseSnCode = async () => {
    getInOutWarehouseSnCodeLoading.value = true
    const data = {
      goodsId: currentOperateCommodity.value.goodsId,
      goodsSpecId: currentOperateCommodity.value.goodsSpecId,
      keyword: keywordCode.value,
      limit: paginationRef.value ? paginationRef.value.size : 50,
      page: paginationRef.value ? paginationRef.value.current : 1,
      storeId: null,
      storePositionId: null,
      type: currentOperateCommodity.value.type,
    }
    const res = await getStoreCodeList(data)
    if (res) {
      totalCode.value = Number(res.data.data.total)
      getListCode.value = res.data.data.rows
      // 重新渲染 产品信息选择
      stockCodeVosTemp.value.map((goods) => {
        getListCode.value.map((item) => {
          if (item.id === goods.id) {
            nextTick(() => {
              selectCodeTableRef.value!.toggleRowSelection(item, undefined)
            })
          }
        })
      })
    }
    getInOutWarehouseSnCodeLoading.value = false
  }

  /**
   * 条码选择事件
   * @param snCodeSelections - 选中的条码
   */
  const handleSnCodeSelectionChange = (snCodeSelections) => {
    commoditys.value[currentOperateCommodity.value.index].stockCodeVosTemp = [
      ..._.cloneDeep(snCodeSelections),
    ]
    if (snCodeAfterSave.value[currentOperateCommodity.value.index]) {
      commoditys.value[currentOperateCommodity.value.index].stockCodeVosTemp = [
        ..._.cloneDeep(snCodeAfterSave.value[currentOperateCommodity.value.index]),
        ..._.cloneDeep(snCodeSelections),
      ]
    }
  }

  /**
   * 跳转到SN详情方法
   * @param snCode - 条码
   */
  const handleToSnCodeDetail = (snCode: SnCode) => {
    selectCodeDialogVisible.value = false
    router.push({ path: `/code/codetail/${snCode.id}/${snCode.tableType}` })
  }

  const cancellationDialog = ref(false)
  const outboundDialog = ref(false)
  const route = useRoute()
  const commoditys = ref()
  const loading = ref(false)
  const DetailStore = ref(null)
  const remark = ref('') //作废消备注
  const ruleFormRef = ref()
  const ruleForm = ref({
    inBoundMaterialVos: [],
    logisticsCode: '', //物流条码
    logisticsName: '', //物流名称
    logisticsNo: '', //物流单号
    remark: '', //出库备注
  })
  const CreateCoderules = ref({
    name: [{ required: true, message: '批次名称', trigger: ['blur', 'change'] }],
  })
  const keywordCode = ref('')

  // 在库选择的选中数据
  const stockCodeVosTemp = ref([])

  // 创建条码
  const CreateCodeDialog = ref(false)
  const createCodeRef = ref()
  const createCode = ref({
    codeVos: [
      {
        goodsId: null, //产品ID
        goodsSpecId: null, //产品规格ID
        qty: '1', //生成条码数量
        warrantyDay: '30', //质保周期/天数
      },
    ],
    name: '', //批次名称
    qty: null, //条码数量
    type: 1, //条码类型：1-成品、2-物料
  })
  // 创建条码弹窗按钮
  const onCreateCode = () => {
    CreateCodeDialog.value = true
    createCode.value = {
      codeVos: [
        {
          goodsId: currentOperateCommodity.value.goodsId, //产品ID
          goodsSpecId: currentOperateCommodity.value.goodsSpecId, //产品规格ID
          qty: currentOperateCommodity.value.qty, //生成条码数量
          warrantyDay: '30', //质保周期/天数
        },
      ],
      name: '', //批次名称
      qty: null, //条码数量
      type: currentOperateCommodity.value.type, //条码类型：1-成品、2-物料
    }
  }
  const paginationRef = ref()
  const totalCode = ref(0)
  const getListCode = ref([])
  // 保存
  const createCodeLoading = ref(false)
  const onaddSave = async () => {
    if (!createCodeRef.value) return
    await createCodeRef.value.validate((valid) => {
      if (valid) {
        createCodeLoading.value = true
        createCode.value.qty = createCode.value.codeVos[0].qty
        let data = _.cloneDeep(createCode.value)

        addSave(data).then((res) => {
          createCodeLoading.value = false
          if (res) {
            ElMessage({
              showClose: true,
              message: res.data.message,
              duration: 5000,
              type: res.data.success ? 'success' : 'error',
              plain: true,
            })
            if (res.data.success) {
              CreateCodeDialog.value = false
              // nextTick(() => {
              getInOutWarehouseSnCode()
              // })
            }
          }
        })
      }
    })
  }

  // 合计
  const getSummaries = (param) => {
    const { columns, data } = param
    const sums: string[] = []
    columns.forEach((column, index: number) => {
      if (index === 0) {
        sums[index] = '合计'
        return
      }
      const values = data.map((item) => Number(item[column.property]))
      if (!values.every((value) => Number.isNaN(value))) {
        switch (index) {
          // case 13:
          //   sums[index] = `￥${values
          //     .reduce((prev, curr) => {
          //       const value = Number(curr)
          //       if (!Number.isNaN(value)) {
          //         return prev + curr
          //       } else {
          //         return prev
          //       }
          //     }, 0)
          //     .toFixed(2)}`
          //   break
          // case 12:
          //   sums[index] = `￥${data
          //     .map((item) => item.price)
          //     .reduce((prev, current) => (Number(prev) || 0) + (Number(current) || 0), 0)
          //     .toFixed(2)}`
          //   break
          case 11:
            sums[index] = `${values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!Number.isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)}`
            break
        }
      } else {
        sums[index] = ''
      }
    })

    return sums
  }
  const resetForm = () => {
    if (!ruleFormRef.value) return
    ruleFormRef.value.resetFields()
    outboundDialog.value = false
  }
  // 根据仓库ID获取仓库详情
  const getDetailStoreItem = async () => {
    if (!route.params.id) return
    loading.value = true
    await getInboundDetail(route.params.id).then((res) => {
      if (res) {
        if (res.data.code == 20000) {
          DetailStore.value = res.data.data.row
        } else {
          ElMessage({
            showClose: true,
            message: res.data.message,
            type: 'error',
            duration: 5000,
            plain: true,
          })
        }
      }
    })
    loading.value = false
  }

  //产品信息
  const getoutStoreList = async () => {
    loading.value = true
    if (route.params.id) {
      const res = await getInboundDetailMaterial(route.params.id)
      if (res) {
        if (res.data.code == 20000) {
          commoditys.value = res.data.data.row.map((o, index) => {
            snCodeAfterSave.value[index] = _.cloneDeep(o.stockCodeVos)
            return { ...o, stockCodeVosTemp: o.stockCodeVos }
          })
        } else {
          ElMessage({
            showClose: true,
            message: res.data.message,
            type: 'error',
            duration: 5000,
            plain: true,
          })
        }
      }
    }
    loading.value = false
  }
  watch(
    () => ruleForm.value.logisticsName,
    (n) => {
      if (n) {
        modules.value.map((o) => {
          if (o.name == n) {
            ruleForm.value.logisticsCode = o.code
          }
        })
      } else {
        ruleForm.value.logisticsCode = ''
      }
    },
  )
  const modules = ref(null)
  const loadingEmp = ref(false)
  const logisticsName = ref('')
  const inputValueSch = (val) => {
    logisticsName.value = val
  }
  watch(logisticsName, (n) => {
    getLogisticsSelectListArr(n)
  })

  // 获取物流列表
  async function getLogisticsSelectListArr(val) {
    loadingEmp.value = true
    let data = {
      limit: 0,
      name: val,
      page: 0,
    }
    await getLogisticsSelectList(data).then((res) => {
      if (res.data.success) {
        modules.value = res.data.data.rows
      } else {
        ElMessage({
          showClose: true,
          message: res.data.message,
          duration: 5000,
          type: 'error',
          plain: true,
        })
      }
      loadingEmp.value = false
    })
  }

  // 作废
  const cancellationBtn = () => {
    cancellationDialog.value = true
  }

  // 确认作废
  const cancellationLoading = ref(false)
  const cancellationConfirm = () => {
    let data = {
      remark: remark.value,
    }
    cancellationLoading.value = true
    cancelStoreInbound(data, route.params.id).then((res) => {
      if (res) {
        ElMessage({
          showClose: true,
          message: res.data.message,
          type: res.data.success ? 'success' : 'error',
          duration: 5000,
          plain: true,
        })
        if (res.data.success) {
          cancellationDialog.value = false
          getDetailStoreItem()
        }
        cancellationLoading.value = false
      }
    })
  }
  // 入库
  const outboundBtn = () => {
    outboundDialog.value = true
    getLogisticsSelectListArr('')
  }
  // 确认入库
  const confirmIntoStorageLoading = ref(false)
  const outboundConfirm = async () => {
    if (!ruleFormRef.value) return
    await ruleFormRef.value.validate((valid) => {
      if (valid) {
        confirmIntoStorageLoading.value = true
        ruleForm.value.inBoundMaterialVos = commoditys.value.map((o) => {
          return {
            stockCodeVos: o.stockCodeVos,
            goodsId: o.goodsId,
            goodsSpecId: o.goodsSpecId,
            id: o.id,
            price: o.price,
            qty: o.qty,
            remark: o.remark,
            storeId: o.storeId,
            storePositionId: o.storePositionId,
            type: o.type,
          }
        })
        saveSureStoreInbound(ruleForm.value, route.params.id).then((res) => {
          if (res) {
            ElMessage({
              showClose: true,
              message: res.data.message,
              type: res.data.success ? 'success' : 'error',
              duration: 5000,
              plain: true,
            })
            if (res.data.success) {
              outboundDialog.value = false
              getDetailStoreItem()
            }
          }
          confirmIntoStorageLoading.value = false
        })
      }
    })
  }
  // 打印
  const printBtn = () => {
    ElMessage({
      showClose: true,
      message: '正在维护升级中，敬请期待...',
      type: 'success',
      duration: 5000,
      plain: true,
    })
  }

  const tagsViewStore = useTagsViewStore()

  const intoStorageInfoRef = ref<HTMLDivElement | null>(null)
  const intoStorageInfoHeight = () => {
    if (intoStorageInfoRef.value) {
      return intoStorageInfoRef.value.scrollHeight
    }
    return 0
  }

  const operateInfoRef = ref<HTMLDivElement | null>(null)
  const getOperateInfoHeight = () => {
    if (operateInfoRef.value) {
      return operateInfoRef.value.scrollHeight
    }
    return 0
  }

  const logisticsInfoRef = ref<HTMLDivElement | null>(null)
  const getLogisticsInfoHeight = () => {
    if (logisticsInfoRef.value) {
      return logisticsInfoRef.value.scrollHeight
    }
    return 0
  }

  const productInfoStyle = ref<CSSProperties>({})
  const setProductInfoStyle = () => {
    productInfoStyle.value.height = `calc(100% - ${intoStorageInfoHeight()}px - ${getOperateInfoHeight()}px - ${getLogisticsInfoHeight()}px - 36px)`
  }

  onMounted(async () => {
    await getDetailStoreItem()
    await getoutStoreList()
    setProductInfoStyle()
    window.addEventListener('resize', setProductInfoStyle)
  })

  watch(
    tagsViewStore.getReloadPages,
    (value) => {
      if (value.includes(route.path)) {
        window.removeEventListener('resize', setProductInfoStyle)
      }
    },
    { immediate: true, deep: true },
  )
</script>

<style lang="scss" scoped>
  @import './detail';
</style>
